package com.harmonypilot.modelconfig.service;

import com.harmonypilot.modelconfig.crypto.CryptoService;
import com.harmonypilot.modelconfig.domain.ModelConfig;
import com.harmonypilot.modelconfig.dto.ModelConfigRequest;
import com.harmonypilot.modelconfig.domain.Priority;
import com.harmonypilot.modelconfig.repo.ModelConfigRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ModelConfigAppService {
    private final ModelConfigRepository repo;
    private final CryptoService crypto;

    public ModelConfigAppService(ModelConfigRepository repo, CryptoService crypto) {
        this.repo = repo; this.crypto = crypto;
    }

    @Transactional
    public ModelConfig upsert(ModelConfigRequest req){
        ModelConfig entity = repo.findByName(req.getName()).orElseGet(ModelConfig::new);
        entity.setName(req.getName());
        entity.setModel(req.getModel());
        entity.setUrl(req.getUrl());
        entity.setDescription(req.getDescription());
        entity.setApiKeyEnc(crypto.encrypt(req.getApiKey()));
        try {
            entity.setPriority(Priority.valueOf(req.getPriority().toUpperCase()));
        } catch (Exception e) {
            entity.setPriority(Priority.MEDIUM);
        }
        return repo.save(entity);
    }

    @Transactional(readOnly = true)
    public List<ModelConfig> list(){
        return repo.findAll();
    }

    @Transactional(readOnly = true)
    public ModelConfig getByName(String name){
        return repo.findByName(name).orElse(null);
    }

    @Transactional
    public void deleteByName(String name){
        repo.deleteByName(name);
    }
}


